//
//  LFBNetTool.m
//  XiMLYa
//
//  Created by dllo on 16/5/11.
//  Copyright © 2016年 Tencent. All rights reserved.
//

#import "LFBNetTool.h"
#import <AFNetworking.h>
#import "Reachability.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation LFBNetTool

+ (void)getNetWithURL:(NSString *)url Body:(id)body Header:(NSDictionary *)header Response:(LFBResponseStyle)response Success:(blockOfSuccess)success Failure:(blockOfFailure)failure
{
    // 1. 获取网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2. 请求头的设置
    if (header) {
        for (NSString *key in header.allKeys) {
            [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
        }
    }
    
    // 3. 设置返回数据的类型
    switch (response) {
        case LFBJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case LFBXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case LFBDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        default:
            break;
    }
    
    // 4. 设置响应数据类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
    
    // 5. iOS9 -- UTF-8转码
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    // 请求 HTTPS
    manager.securityPolicy.allowInvalidCertificates = YES;
    
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    
    NSString *cache = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *resultString = [cache stringByAppendingPathComponent:[self cachedFileNameForKey:url]];
    NSLog(@"%@", resultString);
    
    if ([wifi currentReachabilityStatus] != NotReachable || [conn currentReachabilityStatus] != NotReachable) {
        NSLog(@"使用的wifi");
    
    // 6. 发送请求
        [manager GET:url parameters:body progress:^(NSProgress * _Nonnull downloadProgress) {
            
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
            
            BOOL isCache = [NSKeyedArchiver archiveRootObject:responseObject toFile:resultString];
            if (isCache) {
                NSLog(@"缓存成功");
            }
            else
            {
                NSLog(@"缓存失败");
            }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error);
        NSLog(@"%@", error);
        id data = [NSKeyedUnarchiver unarchiveObjectWithFile:resultString];
        if (data) {
            success(data);
        }
        
    }];
    }
    else
    {
        NSLog(@"使用的缓存");
        id data = [NSKeyedUnarchiver unarchiveObjectWithFile:resultString];
        if (data) {
            success(data);
        }
    }
}

+ (NSString *)cachedFileNameForKey:(NSString *)key {
    const char *str = [key UTF8String];
    if (str == NULL) {
        str = "";
    }
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    NSString *filename = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
                          r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    return filename;
}

+ (void)postNetWithURL:(NSString *)url Body:(id)body BodyStyle:(LFBRequestStyle)bodyStyle Header:(NSDictionary *)header Response:(LFBResponseStyle)response Success:(blockOfSuccess)success Failure:(blockOfFailure)failure
{
    // 1. 获取网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    // 2. 设置body数据类型
    
    switch (bodyStyle) {
        case LFBBodyJSON:
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
        case LFBBodyString:
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable * _Nullable error) {
                return parameters;
            }];
            break;
        default:
            break;
    }
    
    // 3. 请求头的设置
    if (header) {
        for (NSString *key in header.allKeys) {
            [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
        }
    }
    
    // 4. 设置返回数据的类型
    switch (response) {
        case LFBJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case LFBXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case LFBDATA:
            manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
        default:
            break;
    }
    
    // 5. 设置响应数据类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
    
    // 6. iOS9 -- UTF-8转码
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    // 7. 发送请求
    [manager POST:url parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failure(error);
        NSLog(@"%@", error);
    }];
    
}

+ (void)archiverObject:(id)object ByKey:(NSString *)key WithPath:(NSString *)path
{
    // 初始化存储对象信息的data
    NSMutableData *data = [NSMutableData data];
    // 创建归档工具对象
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    // 开始归档
    [archiver encodeObject:object forKey:key];
    // 结束归档
    [archiver finishEncoding];
    // 写入本地
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    NSString *destPath = [[docPath stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:path];
    
    [data writeToFile:destPath atomically:YES];
}

+ (id)unarchiverObjectByKey:(NSString *)key WithPath:(NSString *)path
{
    NSString *docPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    NSString *destPath = [[docPath stringByAppendingPathComponent:@"Caches"] stringByAppendingPathComponent:path];
    NSData *data = [NSData dataWithContentsOfFile:destPath];
    // 创建反归档对象
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    // 接收反归档得到的对象
    id object = [unarchiver decodeObjectForKey:key];
    return object;
}

@end
